<script setup lang="ts">
import { ref } from "vue";
import closeIcon from "@/assets/images/close.png";
import {
  copyInspectionRoute,
  deleteAreaById,
  deleteInspectionRoute,
  getSysDictionaryByType,
  queryInspectionRouteList,
} from "@/api/pipe";
import { useMapStore } from "@/store";
import { useLocalStore } from "@/views/inspection-plan/line/store";
import { useMap } from "@/views/inspection-plan/line/components/Map/index.vue";
const isShowInfoList = ref(true);
const tableData = ref([]);
const currentPage = ref(1);
const total = ref(0);
const background = ref(false);
const disabled = ref(false);
const typeOptions = ref<Array<{ value: number; label: string }>>([]);
const inspLineType = ref<null | number>(null);
const emitEvents = defineEmits(["close"]);
const mapStore = useMapStore();
const localStore = useLocalStore();
const chatbox = ref();
const activeIndex = ref(-1);
const dragx = (el: any) => {
  let oDiv = chatbox.value; //当前元素
  let disX = el.clientX - oDiv.offsetLeft;
  let disY = el.clientY - oDiv.offsetTop;
  document.onmousemove = function (e) {
    //通过事件委托，计算移动的距离
    let l = e.clientX - disX;
    let t = e.clientY - disY;
    if (l < 0) {
      //如果左侧的距离小于0，就让距离等于0.不能超出屏幕左侧。如果需要磁性吸附，把0改为100或者想要的数字即可
      l = 0;
    } else if (l > document.documentElement.clientWidth - oDiv.offsetWidth) {
      //如果左侧的距离>屏幕的宽度-元素的宽度。也就是说元素的右侧超出屏幕的右侧，就让元素的右侧在屏幕的右侧上
      l = document.documentElement.clientWidth - oDiv.offsetWidth;
    }
    if (t < 0) {
      //和左右距离同理
      t = 0;
    } else if (t > document.documentElement.clientHeight - oDiv.offsetHeight) {
      t = document.documentElement.clientHeight - oDiv.offsetHeight;
    }
    //移动当前元素
    oDiv.style.left = l + "px";
    oDiv.style.top = t + "px";
  };
  document.onmouseup = function (e) {
    document.onmousemove = null;
    document.onmouseup = null;
  };
  // 解决有些时候,在鼠标松开的时候,元素仍然可以拖动;
  document.ondragstart = function (ev) {
    ev.preventDefault();
  };
  document.ondragend = function (ev) {
    ev.preventDefault();
  };
  return false;
};

getSysDictionaryByType({
  pageSize: 1000,
  pageIndex: 1,
  dicTypeId: 1,
}).then(({ data, succeeded }: any) => {
  if (succeeded) {
    typeOptions.value = data.items.map((item: any) => {
      const { dictName, dictId } = item;
      return {
        value: dictId,
        label: dictName,
      };
    });
  }
});
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  getData();
};
const handleCopy = (inspLineId: number) => {
  copyInspectionRoute(inspLineId).then(({ succeeded }: any) => {
    if (succeeded) {
      ElMessage("复制成功！");
      getData();
    } else {
      ElMessage("复制失败！");
    }
  });
};
const handleDelete = (inspLineId: number) => {
  deleteInspectionRoute(inspLineId).then(({ succeeded }: any) => {
    if (succeeded) {
      ElMessage("删除成功！");
      getData();
    } else {
      ElMessage("删除失败！");
    }
  });
};
const onTypeChange = (inspLineId: number) => {
  const { setAreaTypeId } = props;
  inspLineType.value = inspLineId;
  getData();
  setAreaTypeId && setAreaTypeId(inspLineId);
};
const getData = () =>
  queryInspectionRouteList({
    pageIndex: currentPage.value,
    pageSize: 5,
  }).then(({ data, succeeded }: any) => {
    if (succeeded) {
      tableData.value = data.items.map((item: any, index: number) => ({
        ...item,
        index: index + 1,
      }));
      total.value = data.totalCount;
    }
  });
const preview = ({ row, $index }: any) => {
  if (activeIndex.value === $index) {
    localStore.setJsonLine(null);
    activeIndex.value = -1;
    return;
  }
  activeIndex.value = $index;
  const { jsonLine } = row;
  localStore.setJsonLine(jsonLine);
};
const goto = (data: any) => {
  const { jsonLine } = data;
  if (jsonLine) {
    try {
      const feature = JSON.parse(jsonLine);
      const bounds = L.geoJSON(feature).getBounds();
      const map = useMap();
      if (map && bounds) {
        map.fitBounds(bounds);
      }
    } catch (e) {}
  }
};
const tableRowClassName = ({
  row,
  rowIndex,
}: {
  row: any;
  rowIndex: number;
}) => {
  if (rowIndex === activeIndex.value) {
    return "selected-row";
  }
  return "";
};
onMounted(() => getData());
const props = defineProps({
  setAreaTypeId: {
    type: Function,
    default: () => 0,
  },
});
</script>

<template>
  <div
    class="info-list"
    v-if="isShowInfoList"
    ref="chatbox"
    @mousedown="dragx($event)"
  >
    <div class="title">
      <span>巡检路线</span>
      <img
        class="close"
        :src="closeIcon"
        @click="
          emitEvents('close');
          localStore.setJsonLine(null);
        "
      />
    </div>
    <el-table
      :data="tableData"
      style="width: 100%; height: 250px; cursor: pointer"
      :row-class-name="tableRowClassName"
    >
      <el-table-column label="预览" width="10%">
        <template #default="scope">
          <el-icon @click="preview(scope)"
            ><View :color="activeIndex === scope.$index ? 'blue' : ''"
          /></el-icon>
        </template>
      </el-table-column>
      <el-table-column label="序号" width="10%">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span>{{ scope.row.index }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="名称" width="15%">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <el-tooltip
              class="box-item"
              effect="dark"
              :content="scope.row.inspLineName"
              placement="top"
            >
              <span
                class="label"
                @click="
                  preview(scope);
                  goto(scope.row);
                "
                style="color: blue"
                >{{ scope.row.inspLineName }}</span
              >
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="类型" width="10%">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span class="label">{{
              ["路线", "区域"][scope.row.inspLineType - 1]
            }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="起点" width="15%">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <el-tooltip
              class="box-item"
              effect="dark"
              :content="
                scope.row.startPositionName +
                '(' +
                scope.row.startPosition.serial +
                ')'
              "
              placement="top"
            >
              <span class="label">{{
                scope.row.startPositionName +
                "(" +
                scope.row.startPositionName.serial +
                ")"
              }}</span>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="终点" width="15%">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <el-tooltip
              class="box-item"
              effect="dark"
              :content="
                scope.row.endPositionName +
                '(' +
                scope.row.endPosition?.serial +
                ')'
              "
              placement="top"
            >
              <span class="label">{{scope.row.endPosition ?
                scope.row.endPositionName +
                "(" +
                scope.row.endPosition.serial +
                ")" : ""
              }}</span>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="25%" style="display: flex">
        <template #default="scope">
          <el-button
            size="small"
            style="width: 30px"
            @click="mapStore.setEditingInspectionRoute(scope.row)"
            >编辑</el-button
          >
          <el-popconfirm
            title="确定复制吗?"
            @confirm="handleCopy(scope.row.inspLineId)"
          >
            <template #reference>
              <el-button size="small" style="width: 30px">复制</el-button>
            </template>
          </el-popconfirm>
          <el-popconfirm
            title="确认要删除选中的路线吗？删除后无法恢复，请谨慎操作!"
            @confirm="handleDelete(scope.row.inspLineId)"
          >
            <template #reference>
              <el-button size="small" type="danger" style="width: 30px"
                >删除</el-button
              >
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div class="pager">
      <el-pagination
        :small="true"
        v-model:current-page="currentPage"
        :page-size="5"
        :pager-count="5"
        :disabled="disabled"
        :background="background"
        layout="total, prev, pager, next"
        :total="total"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<style scoped lang="scss">
.info-list {
  position: absolute;
  top: 255px;
  right: 50px;
  z-index: 1000;
  width: 580px;
  height: auto;
  font-family: Roboto, sans-serif;
  font-size: 14px;
  line-height: 20px;
  color: rgb(16 16 16 / 100%);
  text-align: center;
  background-color: rgb(255 255 255 / 100%);
  border: 1px solid rgb(187 187 187 / 100%);

  :deep(.el-table__header) {
    width: 100% !important;
  }

  :deep(.el-table__body) {
    width: 100% !important;
  }

  :deep(.el-table__cell) {
    height: 40px !important;
  }

  :deep(.selected-row) {
    background-color: #f0f9eb;
  }
}

.el-table .selected-row {
  background-color: #f0f9eb;
}

.title {
  height: 40px;
  padding-left: 10px;
  font-size: 20px;
  background: #1990ff 100%;

  span {
    line-height: 40px;
    color: #fff;
  }

  .close {
    position: relative;
    top: 7px;
    right: 10px;
    float: right;
    cursor: pointer;
  }
}

.search {
  margin: 8px 5px 10px 14px;
}

.label {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.pager {
  float: right;
  margin: 10px;
}
</style>
